package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import com.itheima.utils.AESUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Reference
    private MemberService memberService;

    @Autowired
    private JedisPool jedisPool;

    //会员登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从redis中获取缓存的验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (codeInRedis == null && !codeInRedis.equals(validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        } else {
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //把手机号加密后存入cookie中，用于跟踪用户
            Cookie cookie = new Cookie("login_member_telephone", AESUtils.encryptByAES(telephone, "123"));
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60 * 30, json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }
    }

    //获取会员信息
    @RequestMapping("/getMemberInfo")
    public Result getMemberInfo(HttpServletRequest request) {
        //根据Cookie验证用户身份
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("login_member_telephone")) {
                    //解密
                    String value = AESUtils.decryptByAES(cookie.getValue(), "123");
                    String member = jedisPool.getResource().get(value);
                    if (member != null) {
                        return new Result(true, "查询成功", JSON.parse(member));
                    }
                    break;
                }
            }
        }
        return new Result(false, "查询失败");
    }

    //修改用户信息
    @RequestMapping("/editMemberInfo")
    public Result editMemberInfo(@RequestBody Member memberInfo) {

        try {
            memberService.editMemberInfo(memberInfo);
            return new Result(true, MessageConstant.EDIT_MEMBER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_MEMBER_FAIL);
        }

    }


    //查看当前用户预约记录
    @RequestMapping("/findMemberOrderInfo")
    public Result findMemberOrderInfo(String startTime, String endTime, HttpServletRequest request) {
        //根据Cookie验证用户身份
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return new Result(false, "用户未登录,请先登录");
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("login_member_telephone")) {
                //解密
                String value = AESUtils.decryptByAES(cookie.getValue(), "123");
                String member = jedisPool.getResource().get(value);
                if (member != null) {
                    //用户确认已登录,根据当前用户id,和时间参数查询预约信息
                    Integer memberId = JSON.parseObject(member, Member.class).getId();
                    try {
                        List<Map<String, Object>> list = memberService.findMemberOrderInfo(startTime, endTime, memberId);
                        return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, list);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
                    }
                }
                break;
            }
        }
        return new Result(false, "用户未登录,请先登录");
    }

    //查看当前用户预约详情
    @RequestMapping("/findMemberOrderDetail")
    public Result findMemberOrderDetail(Integer orderId) {
        try {
            Map<String, Object> map = memberService.findMemberOrderDetail(orderId);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }


}
